import requests
import time
import json
import gzip
from pyquery import PyQuery

# 维持cookie
req = requests.Session()


def parsePage(content):
    '''解析爬取网页中内容，并返回结果'''
    # ========使用pyquery解析======================
    # 初始化，返回Pyquery对象
    doc = PyQuery(content)
    items = doc("div.item-form")
    # 遍历并解析件商品
    for item in items.items():
        yield {
            'title': item.find("div.p-name a").text(),
            'image': "http:"+item.find("div.p-img img").attr('src'),
            'singlePrice': item.find("div.cell.p-price.p-price-new strong").text(),
            'num': item.find("div.cell.p-quantity input").attr('value'),
            'totalPrice': item.find("div.cell.p-sum strong").text()
        }


def main():
    """爬取京东购物车信息"""
    url = 'https://cart.jd.com/cart.action'
    # 封装headers头信息
    headers = {
        'Accept': 'application/json, text/javascript, */*; q = 0.01',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'cache-control': 'max-age=0',
        'referer': 'https://cart.jd.com/cart.action',
        'upgrade-insecure-requests': '1',
        'cookie': 'CCC_SE=ADC_P9x%2fRbzIw8tardeorwu71NCr6cyqs2wxFj360onLhwHSANWSVOfFiAd5923OaTuky5NGb%2f%2fjyBoN5DzXetThhMndq6oNi17yMDNmWAgRXXbke5sdKgIGmZY6ZmdjQXerqcKwUZBd3qaV3PPv7nN1H8JIwXpUl3mAL4oa3abh5wh1V9aW0ufSP37NN4UCjUnV6zRigKQTCZ3JP%2fE4WJ561Sv0C2vmaqjgVp41lnwcgOE6mG3Eel1jeLb3mR%2fnyRN9fk5zXHHiA7OeewclGdyUIcexNejnhZzvLkgdFltZBOjC19dCxgNVKNswSJ2oPgwWJfXoNPaFSVDg6M36a80KxrWJoBI7NkEW70ttI295JVQL7c8IILnEPhDLZPj5GSArEKJnJXu%2bihK9Pj9MIU5VQCoYSeN%2fD8QTF2s4JMK%2fEa9GpsggI7P2TYZhREmgHiGY4lwoZriZGjOhwnjquZOOCcn9lhIDMCZYi%2fin%2fM1pnGMS8TOZWwsXhwlVoH%2f0qFiW; __jdc=122270672; user-key=61ff4c4f-2be4-42e4-aa02-c7a3d7d748f9; cd=0; shshshfpa=f4283276-46c0-3097-0127-26cc534edcc3-1547472396; __jdv=122270672|direct|-|none|-|1547472396735; __jdu=15474723967342137792604; 3AB9D23F7A4B3C9B=RUSNH5B6A5XCBMSJ7LOBS6UZBTXXG4UCOTD5X3R5QNXNQ3M7GW54K2MK6PDN3I34CGXAINYKEMUJIPNC2CKQSIO3OQ; cart-main=xx; ipLoc-djd=1-72-2819; _gcl_au=1.1.1761815219.1547473586; shshshfpb=fuOCyMJqn2m7b%20NIIlgHYQw%3D%3D; cn=13; shshshfp=26fde8312a785e776b9a65330c2d9ed3; __jda=122270672.15474723967342137792604.1547472397.1547472397.1547730690.2; shshshsID=6ffe01863bf741165eb28b06f9175772_3_1547730816497; __jdb=122270672.3.15474723967342137792604|2.1547730690',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
    }

    # 发送请求，抓取信息
    res = req.post(url, headers=headers)

    # print(html)
    for item in parsePage(res.text):
        with open("./result2.txt", 'a', encoding="utf-8") as f:
            f.write(json.dumps(item, ensure_ascii=False)+"\n")


    # 判断当前执行是否为主程序，并遍历调度主函数来爬取信息
if __name__ == '__main__':
    main()
    time.sleep(1)
